﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ELab.Client;
using ELab.Message;
using ELab.QuestionAnwer;
using ELab.Serialization.Data;
using ELab.Communication.Messages;
using ELab.View.TestExample;
using ELab.Management;
using ELab.Settings;
using ELab.Communication;
using ELab.Communication.Messages.ControllerMessages;

namespace ELab.Student.Controls
{
    public partial class ctrlDoTestSample : UserControl
    {        
        // Public variable
        public ELabClient _student;
        public LessonTest examp;
        public int timeRemaining = 0;
        public int index = 0;
        private List<QuestionResult> results;
        private Question currentQuestion = new Question();
        private bool isSent = false;
        public User CurrentUser = null;
        public event EventHandler RaiseComplete;
        public event EventHandler RaiseGetIndex;
        public event EventHandler RaiseChangeIndex;
        public IEnumerable<User> Users { get; set; }
        public ClassMode viewMode;

        public ctrlDoTestSample()
        {
            InitializeComponent();
        }

        public void LoadQuestionForm()
        {
            RaiseGetIndex(null, null);
            // clear panel
            flowLayoutPanel1.Controls.Clear();
            // Initialize result
            if (results == null)
                results = examp.Questions.Select(c => new QuestionResult() { Question = c, Result = string.Empty }).ToList();
           
            // set issent result is false
            isSent = false;
            
            currentQuestion = examp.Questions[index];

            Label questionLabel = new Label();
            questionLabel.Width = flowLayoutPanel1.Width - 30;
            questionLabel.Text = string.Format("Question: {0}", currentQuestion.QuestionValue);
            flowLayoutPanel1.Controls.Add(questionLabel);

            foreach (Answer answer in currentQuestion.Answers)
            {
                RadioButton rd = new RadioButton();
                rd.Name = "rdAnswer";
                rd.Text = answer.AnswerValue;
                rd.Width = flowLayoutPanel1.Width - 30;
                rd.Padding = new System.Windows.Forms.Padding(20, 0, 0, 0);
                flowLayoutPanel1.Controls.Add(rd);
            }
        }
        public void SentResult()
        {
            RaiseComplete(this, null);
            if (isSent) return;

            TestExampleResult testresult = new TestExampleResult()
            {
                Results = results,
                Student = CurrentUser.Fullname,
                Mark = string.Format("{0}/{1}", results.Where(r=>r.Result.Equals(r.Question.Answers.FirstOrDefault(q=>q.IsRightAnwer).AnswerValue)).Count(), examp.Questions.Count)
            };
            var dataArr = testresult.SerializeToByteArray();
            CommandMessage comm = new CommandMessage { CommandType = CommandType.RequestTestResult, Body = dataArr };
            EMessage mess = new EMessage { Command = comm };

            var ms = _student.CreateMessage();
            ms.DestinationApplicationName = this.Users.FirstOrDefault(u=>u.Type == UserType.Teacher).UserName;
            ms.MessageData = mess.Data;
            ms.TransmitRule = MessageTransmitRules.NonPersistent;
            ms.Send();

            isSent = true;
            // prepare data to send
            dataArr = new UserMessage() { UserName = CurrentUser.UserName, Question_Index = index, Time_Remaining = timeRemaining }.SerializeToByteArray();
                        
            // raise a message for complete testing user
            var testRightAnswer = CheckResult();
            if (testRightAnswer)
            {
                comm = new CommandMessage { CommandType = CommandType.RequestCompleteSample, Body = dataArr };
            }
            else
            {
                comm = new CommandMessage { CommandType = CommandType.RequestFreeHand, Body = dataArr };
            }
            mess = new EMessage { Command = comm };

            foreach (var user in this.Users)
            {
                ms = _student.CreateMessage();
                ms.DestinationApplicationName = user.UserName;
                ms.MessageData = mess.Data;
                ms.TransmitRule = MessageTransmitRules.NonPersistent;
                ms.Send();
            }
            results = null;
        }

        private void btnNext_Click(object sender, EventArgs e)
        {
            var this_result = GetCurrentResult();
            
            if (viewMode == ClassMode.TESTING)
            {
                while (flowLayoutPanel1.Controls.Find("rdAnswer", false).Count() > 0)
                    flowLayoutPanel1.Controls.RemoveByKey("rdAnswer");
                index++;
                RaiseChangeIndex(sender, e);
                if (index == examp.Questions.Count)
                {
                    SentResult();
                    return;
                }
                currentQuestion = examp.Questions[index];
                LoadQuestionForm();
            }
            else if (viewMode == ClassMode.TESTING_HANDUP)
            {
                if (this_result)
                {
                    while (flowLayoutPanel1.Controls.Find("rdAnswer", false).Count() > 0)
                        flowLayoutPanel1.Controls.RemoveByKey("rdAnswer");
                    index++;
                    RaiseChangeIndex(sender, e);
                    if (index == examp.Questions.Count)
                    {
                        SentResult();
                        return;
                    }
                    currentQuestion = examp.Questions[index];
                    LoadQuestionForm();
                }
                else
                {
                    SentResult();
                }
            }
        }

        private bool GetCurrentResult()
        {
            var rds = flowLayoutPanel1.Controls.Find("rdAnswer", false);
            foreach (var item in rds)
            {
                RadioButton rd = (RadioButton)item;
                if (rd.Checked) { results[index].Result = rd.Text; break; }
            }

            return results[index].Question.Answers.FirstOrDefault(a => a.IsRightAnwer).AnswerValue == results[index].Result;
        }

        private void EnableForm(bool isEnable)
        {
            flowLayoutPanel1.Enabled = isEnable;
            groupBox1.Enabled = isEnable;
            btnFinished.Enabled = isEnable;
            btnNext.Enabled = isEnable;
            lbTimeRemaining.Enabled = isEnable;
            label1.Enabled = isEnable;
        }

        private void btnFinished_Click(object sender, EventArgs e)
        {
            GetCurrentResult();
            SentResult();
        }

        private bool CheckResult()
        {
            if (results.Count < examp.Questions.Count)
                return false;
            foreach (var result in results)
            {
                if(!result.Result.Equals(result.Question.Answers.FirstOrDefault(a=>a.IsRightAnwer).AnswerValue))
                {
                    return false;
                }
            }
            return true;
        }

        public void FinishTesting()
        {
            GetCurrentResult();
            SentResult();
        }
    }
}
